<template>
  <div>
    <!--聊天页面-->
    <el-card class="chat-page">
      <!--对话窗口-->
      <div class="chat-windows">
        <ChatWindows ref="chat-windows-method"></ChatWindows>
      </div>
      <!--输入框范围-->
      <div class="input-frame">
        <el-input
            v-model="inputValue"
            :autosize="{ minRows: 2, maxRows: 2 }"
            type="textarea"
            placeholder="输入你的问题"
        />
        <div class="submit-button">
          <el-button type="primary" :icon="Edit" style="width: 120%" @click="handleSendButton"/>
        </div>
      </div>
    </el-card>
  </div>

</template>
<script>
import {Delete, Edit, Search, Share, Upload} from '@element-plus/icons-vue'
import ChatWindows from "@/components/Note/SparkAi/ChatWindows.vue";
import {JsonConnectObject} from '@/utils/custom-connect-json';
import {customPost} from '@/utils/custom-connect'

export default {
  name: "SparkTextDialogue",
  data() {
    return {
      Edit,
      inputValue: '',
      webSocketObject:null
    }
  },
  components: {ChatWindows},
  created() {
    this.websocketInit();
  },
  methods: {
    submitQuestion() {
      this.$refs["chat-windows-method"].userAsk(this.inputValue)
      let jco = new JsonConnectObject()
          .setUrl("/spark/Ai")
          .setData({
            question:this.inputValue
          })
          .setHeaders({
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          })
      this.inputValue = ''
      customPost(jco.url,jco.data,jco.headers).then(res => {
        console.log(res)
        this.$refs["chat-windows-method"].aiAnswer(res.data)
      })
    },
    handleSendButton(){
      this.submitQuestion()
    },
    websocketInit(){
      const webSocketUrl = 'ws://localhost:8080/websocket/zhangsan'
      try {
        this.webSocketObject = new WebSocket(webSocketUrl)
      } catch (error) {
        console.log(error)
      }
      this.webSocketObject.onopen = (e) => this.webSocketOnOpen(e)
      this.webSocketObject.onmessage = (e) => this.webSocketOnMessage(e)
      this.webSocketObject.onerror = (e) => this.webSocketOnError(e)
      this.webSocketObject.onclose = (e) => this.webSocketOnClose(e)
    },
    webSocketOnOpen(e){
      console.log('与服务器连接打开'+e)
      this.webSocketObject.send(JSON.stringify({
        question: this.inputValue
      }));
    },
    webSocketOnMessage(e){
      // console.log('来自服务器的消息:'+e)
      console.log(e.data)
    },
    webSocketOnError(e){
      console.log('与服务器连接异常:'+e)
    },
    webSocketOnClose(e){
      console.log('与服务器关闭->'+e)
    },
  },
}
</script>

<style scoped>
.chat-page {
  position: relative;
  margin: 5px 10% 0; /*上 左 下*/
  width: 80%;
  height: 500px;
}

/*输入框样式*/
.input-frame {
  position: absolute;
  bottom: 1px;
  width: 95%;
  display: flex;
}

/*按钮样式*/
.submit-button {
  position: relative;
  left: 1%;
  margin-top: 1%;
}

/*对哈窗口样式*/
.chat-windows {
  position: relative;
  height: 420px;
  width: 100%;
}
</style>
